package com.lelouch.service;

import com.google.common.base.Preconditions;
import com.lelouch.bean.SysDept;
import com.lelouch.bean.SysUser;
import com.lelouch.common.RequestHolder;
import com.lelouch.dao.SysDeptMapper;
import com.lelouch.dao.SysLogMapper;
import com.lelouch.dao.SysUserMapper;
import com.lelouch.exception.ParamException;
import com.lelouch.param.DeptParam;
import com.lelouch.util.BeanValidator;
import com.lelouch.util.IpUtil;
import com.lelouch.util.LevelUtil;
import lombok.experimental.PackagePrivate;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 部门服务
 *
 * @author lcy
 * @create 2018-06-12 15:08
 */
@Service
public class SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysLogService sysLogService;

    public void save(DeptParam deptParam) {
        //检查参数是否合法
        BeanValidator.check(deptParam);
        //检查部门名是否重复
        if (checkExist(deptParam.getParentId(), deptParam.getName(), deptParam.getId())) {
            throw new ParamException("当前层级下已经有同名的部门名称，请重新命名！");
        }
        //生成level的名称
        String level = LevelUtil.calculateLevel(getLevel(deptParam.getParentId()), deptParam.getParentId());
        SysDept sysDept = SysDept.builder().name(deptParam.getName()).level(level).parentId(deptParam.getParentId())
                .seq(deptParam.getSeq()).remark(deptParam.getRemark()).build();
        sysDept.setOperator(RequestHolder.getUser().getUsername());
        sysDept.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getRequest()));
        sysDept.setOperateTime(new Date());
        sysDeptMapper.insertSelective(sysDept);
        sysLogService.saveDeptLog(null,sysDept);
    }

    public boolean checkExist(Integer parentId, String deptName, Integer deptId) {
        return sysDeptMapper.countByNameAndParentId(parentId, deptName, deptId) > 0;
    }

    public String getLevel(Integer deptId) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (sysDept == null) {
            return null;
        }
        return sysDept.getLevel();
    }

    public void update(DeptParam deptParam) {
        //检查参数是否合法
        BeanValidator.check(deptParam);
        //检查部门名是否重复
        if (checkExist(deptParam.getParentId(), deptParam.getName(), deptParam.getId())) {
            throw new ParamException("当前层级下已经有同名的部门名称，请重新命名！");
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(deptParam.getId());
        Preconditions.checkNotNull(before, "待更新的部门不存在");


        //生成level的名称
        String level = LevelUtil.calculateLevel(getLevel(deptParam.getParentId()), deptParam.getParentId());
        SysDept after = SysDept.builder().id(deptParam.getId()).name(deptParam.getName()).level(level).parentId(deptParam.getParentId())
                .seq(deptParam.getSeq()).remark(deptParam.getRemark()).build();
        after.setOperator(RequestHolder.getUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getRequest()));
        after.setOperateTime(new Date());
        updateWithChild(before, after);
        sysLogService.saveDeptLog(before,after);
    }


    @Transactional
    public void updateWithChild(SysDept before, SysDept after) {
        String oldLevel = before.getLevel();
        String newLevel = after.getLevel();
        if (!StringUtils.equals(oldLevel, newLevel)) {
            List<SysDept> sonDepts = sysDeptMapper.getChildDeptListByLevel(oldLevel + ".%");
            if (CollectionUtils.isNotEmpty(sonDepts)) {
                for (SysDept sysDept : sonDepts) {
                    String level = sysDept.getLevel();
                    if (level.indexOf(oldLevel) == 0) {
                        level = newLevel + level.substring(oldLevel.length());
                        sysDept.setLevel(level);
                    }
                }

                sysDeptMapper.batchUpdateLevel(sonDepts);
            }
        }

        sysDeptMapper.updateByPrimaryKey(after);


    }

    public void delele(Integer deptId) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
        Preconditions.checkNotNull(sysDept, "所删除的部门不存在！");
        if (sysDeptMapper.countByParentId(deptId) > 0) {
            throw new ParamException("所删除的部门存在有子部门，不可删除！");
        }
        if(sysUserMapper.getUserCountByDeptId(deptId)>0){
            throw new ParamException("所删除的部门里存在用户，不可删除！");
        }
        sysDeptMapper.deleteByPrimaryKey(deptId);
    }
}
